package com.lollipop.synthential.proxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @Author: J.K
 * @Date: 2021-02-24 18:58
 * @Description: JDK动态代理：必须提供接口才能用
 */
public class JdkProxy {
    public static void main(String[] args) {
        JDKProxyTestInterface target = new JDKProxyTestInterfaceImpl();
        // 根据目标对象创建代理对象
        JDKProxyTestInterface proxy = (JDKProxyTestInterface) Proxy.newProxyInstance(target.getClass().getClassLoader(),
                target.getClass().getInterfaces(), new JDKProxyTestInvocationHandler(target));
        // 调用代理对象方法
        proxy.testProxy();
    }

    /**
     * 测试代理接口
     */
    interface JDKProxyTestInterface {
        /**
         * 测试JDK动态代理
         */
        void testProxy();
    }

    /**
     * 接口具体实现类
     */
    static class JDKProxyTestInterfaceImpl implements JDKProxyTestInterface {
        @Override
        public void testProxy() {
            System.out.println("testProxy");
        }
    }

    /**
     * 实现InvocationHandler接口
     */
    static class JDKProxyTestInvocationHandler implements InvocationHandler {
        // 需要代理的对象作为代理类的属性
        private Object target;

        JDKProxyTestInvocationHandler(Object target) {
            this.target = target;
        }

        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            System.out.println("执行前");
            Object result = method.invoke(this.target, args);
            System.out.println("执行后");
            return result;
        }
    }
}
